package com.ht.shop.controller;

import com.alibaba.druid.util.StringUtils;
import com.ht.shop.annotations.RequestMapping;
import com.ht.shop.converts.MyDateConvert;
import com.ht.shop.pojo.PageBean;
import com.ht.shop.pojo.TbGoods;
import com.ht.shop.pojo.TbGoodsKz;
import com.ht.shop.service.GoodsService;
import com.ht.shop.service.impl.GoodsServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@RequestMapping("/goods")
public class GoodsServlet {
    private GoodsService goodsService = new GoodsServiceImpl();

    @RequestMapping("/add")
    public String addGoods(HttpServletRequest req, HttpServletResponse resp) throws FileUploadException, IOException {

        TbGoodsKz tbGoodsKz = new TbGoodsKz();
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
        List<FileItem> items = servletFileUpload.parseRequest(req);


        List<FileItem> picture = items.stream().filter(item -> {
            return item.getFieldName().equals("picture");
        }).collect(Collectors.toList());
        if (picture == null || picture.size() == 0) {
            resp.setContentType("text/html;charset=utf-8");
            try {
                resp.getWriter().write("没有传递图片");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        String realPath = req.getServletContext().getRealPath("/pic/");
        System.out.println("获取到的图片的路径。。。"+realPath);
        File path =new File(realPath);
        if (!path.exists()) {
            path.mkdirs();//创建目录
        }
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        String uploadFileName = picture.get(0).getName();
        System.out.println("名字==="+uploadFileName);
        fileName = fileName+uploadFileName.substring(uploadFileName.lastIndexOf("."));
        System.out.println("新的名字=="+fileName);
        IOUtils.copy(picture.get(0).getInputStream(),new FileOutputStream(realPath+fileName));

        String savePath = "/pic/" + fileName;
        try {
            Map<String,String> map = items.stream().filter(item ->{
                return !item.getFieldName().equals("picture");
            }).collect(Collectors.toMap(FileItem::getFieldName,fileItem -> {
                try {
                    return fileItem.getString("UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return null;
            }));

            List<FileItem> priceList = items.stream().filter(item ->{
                return item.getFieldName().equals("price");
            }).collect(Collectors.toList());
            double priceDouble = Double.parseDouble(priceList.get(0).getString());

            ConvertUtils.register(new MyDateConvert(), Date.class);
            BeanUtils.populate(tbGoodsKz, map);

            tbGoodsKz.setPrice(((long) (priceDouble * 10)));
            tbGoodsKz.setPicture(savePath);
            System.out.println("封装后的数据"+tbGoodsKz);
            goodsService.addGoods(tbGoodsKz);

            return "redirect:/admin/success.jsp";
        } catch (IllegalAccessException e) {
            e.printStackTrace();

        } catch (InvocationTargetException e) {
            e.printStackTrace();

        } catch (Exception e) {
            e.printStackTrace();

        }
        return "redirect:/admin/fail.jsp";
    }
    @RequestMapping("/show")
    public String show(HttpServletRequest request, HttpServletResponse response) {
        //查询数据,保存到 request中
        String id = request.getParameter("id");//分类 id
        String currentPage = request.getParameter("currentPage");//当前页码
        int currentPageNum = 1;//默认是第一页
        int typeId = Integer.parseInt(id);//将分类 id 转换为 int

        if (currentPage != null && !"".equalsIgnoreCase(currentPage.trim())) {
            currentPageNum = Integer.parseInt(currentPage);//传递了当前页的时候使用当前页
        }

        try {
            PageBean<TbGoods> pageBean = goodsService.getGoodsPageByTypeId(typeId, currentPageNum);
            request.setAttribute("pageBean", pageBean);//保存了数据,跳转页面
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "forward:/goodsList.jsp";
    }

    @RequestMapping("/detail")
    public String detail(HttpServletRequest request, HttpServletResponse response) {
        //查询数据,保存到 request中
        String id = request.getParameter("id");//分类 id
        if (StringUtils.isEmpty(id)) {
            return "redirect:/error/error.jsp";
        }
        TbGoods tbGoods = goodsService.getGoodById(Integer.parseInt(id));
        request.setAttribute("product", tbGoods);
        return "forward:/goodsDetail.jsp";
    }
}
